<template>
  <!-- 地址信息 -->
  <van-contact-card type="edit" :tel="address.mobile" :name="address.consignee" @click="toAddrssPages"
      v-if="Object.values(address).length > 0" />
  <van-contact-card type="add" @click="toAddrssPages" v-else />
  <!-- 购物车商品信息 -->
  <van-card v-for="item in cartlist" :key="item.id" :price="item.total" :num="item.nums"
      :thumb="item.product.thumbs_text">
      <template #title>
          <h3>{{ item.product.name }}</h3>
      </template>
      <template #desc>
          <div v-if="item.attrs">
              <van-tag v-for="items in item.attrs" type="primary" size="large" style="margin-right: 10px;">{{
                  items.value }}</van-tag>
          </div>
          <div v-else>
              <van-tag type="danger" size="large" style="margin-right: 10px;">无商品规格</van-tag>
          </div>
          <h4>单价: {{ item.price }}</h4>
      </template>
  </van-card>

  <!-- 支付方式 -->
  <van-field v-model="payName" is-link readonly label="支付方式" placeholder="选择支付方式" @click="showPicker = true" />
  <van-popup v-model:show="showPicker" round position="bottom">
      <van-picker :columns="columns" @cancel="showPicker = false" @confirm="onConfirm" />
  </van-popup>

  <!-- 优惠券单元格 -->
  <van-coupon-cell :coupons="couponlist" :chosen-coupon="chosenCoupon" @click="showList = true" />
  <!-- 优惠券列表 -->
  <van-popup v-model:show="showList" round position="bottom" style="height: 90%; padding-top: 4px;">
      <van-coupon-list :coupons="couponlist" :chosen-coupon="chosenCoupon" @change="onChange"
          :show-exchange-bar="false" />
  </van-popup>

  <!-- 订单备注 -->
  <van-field v-model="remark" rows="2" autosize label="订单备注" type="textarea" maxlength="120" placeholder="请输入订单备注"
      show-word-limit />

  <!-- 提交订单 -->
  <van-submit-bar :price="total" button-text="确认支付" @submit="onSubmit" />

</template>
<script setup>
const { proxy } = getCurrentInstance()
const LoginUser = reactive(proxy.$cookies.get('LoginUser'));
const cartids = ref(proxy.$route.query.cartids ?? 0)
const address = ref(proxy.$cookies.get('address') ?? {})
const cartlist = ref([])
const remark = ref('')
const columns = [
  { text: '余额', value: 'money' },
  { text: '微信', value: 'wx' },
  { text: '支付宝', value: 'zfb' }
];

//优惠券
const payName = ref('');
const showPicker = ref(false);
const pay = ref('')

const onConfirm = ({ selectedOptions }) => {
  showPicker.value = false;
  payName.value = selectedOptions[0].text;
  pay.value = selectedOptions[0].value;
};

const couponlist = ref([]);
const showList = ref(false);
const chosenCoupon = ref(-1);

const onChange = (index) => {
  showList.value = false;
  chosenCoupon.value = index;
};


onBeforeMount(() => {
  getCartData()
  if (JSON.stringify(address.value) == '{}') {
      getAddressSelected()
  }
  getCouponData()
})
const getCartData = async () => {
  let result = await Api.CartIndex({
      busid: LoginUser.id,
      cartids: cartids.value
  })

  if (result.code == 1) {
      cartlist.value = result.data
        
      cartlist.value.forEach(item => {
          if (item.attrs) {
              item.attrs = JSON.parse(item.attrs)
          }
      })
  }
}

const getAddressSelected = async () => {
  let result = await Api.AddressOrder({
      busid: LoginUser.id
  })

  if (result.code == 1) {
      address.value = result.data
      proxy.$cookies.set("address", {
          id: result.data.id,
          consignee: result.data.consignee,
          mobile: result.data.mobile
      });
  }
}

const getCouponData = async () => {
  let result = await Api.CouponOrder({
      busid: LoginUser.id
  })

  if (result.code == 1) {
      result.data.forEach((item) => {
          couponlist.value.push({
              id: item.id,
              condition: '正在活动中',
              value: 0,
              name: item.coupon.title,
              startAt: item.coupon.createtimes,
              endAt: item.coupon.endtime,
              valueDesc: parseFloat(item.coupon.rate) * 100,
              unitDesc: '折',
              rate: item.coupon.rate
          })
      })
  }
}



const toAddrssPages = () => {
  proxy.$router.push({
      path: '/business/address/index',
      query: {
          action: 'order'
      }
  })
}

// 计算
const total = computed(() => {
  let num = 0
  num = cartlist.value.reduce((accumulator, item) => accumulator + parseFloat(item.total), 0,);
  if (chosenCoupon.value != '-1') {
      let totals = cartlist.value.reduce((accumulator, item) => accumulator + parseFloat(item.total), 0,);
      let rate = parseFloat(couponlist.value[chosenCoupon.value].rate)
      // 打折之后的价格
      num = (totals * rate).toFixed(2)
      // 优惠券金额
      let price = (totals - num) * 100
      couponlist.value[chosenCoupon.value].value = price
  }

  return num * 100
})

const onSubmit = async () => {

  if(JSON.stringify(address.value) == '{}')
  {
      error('请选择收货地址');
      return false;
  }

  if (!pay.value) {
      error('请选择支付方式');
      return false;
  }

  let data = {
      busid: LoginUser.id,
      businessaddrid: address.value.id,
      amount: total.value / 100,
      remark: remark.value,
      pay: pay.value,
      couponid: chosenCoupon.value != '-1' ? couponlist.value[chosenCoupon.value].id : 0,
      cartids: cartids.value
  }

  let result = await Api.OrderAdd(data)
  if (result.code == 1) {
      success({
          message: result.msg,
          onClose: () => {
              proxy.$router.push('/order/index')
          }
      });
  } else {
      error(result.msg);
  }
}

</script>
<style scoped>
/* 组件穿透样式写法 */
:deep .van-field__control:read-only {
  text-align: right;
}
</style>